package com.bjb.util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;

/**
 * 给bean对象的时间注入当时间值以及删除标识
 */
public class BeanHelper {

  private static final String updateDatetimeKey  = "updateDatetime";

  private static final String createDatetimeKey  = "createDatetime";

  private static final String updateUserIdKey = "updateUserId";

  private static final String createUserIdKey = "createUserId";

  private static final String delFlgKey = "delFlg";


  public static <T> void setDefaultProp(T target,Class<T> clazz) {
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor propertyDescriptor : descriptors) {
      String fieldName = propertyDescriptor.getName();
      Object value;
      try {
        value = PropertyUtils.getProperty(target,fieldName );
      } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new RuntimeException("can not set property  when get for "+ target +" and clazz "+clazz +" field "+ fieldName);
      }
      if (String.class.isAssignableFrom(propertyDescriptor.getPropertyType()) && value == null) {
        try {
          PropertyUtils.setProperty(target, fieldName, "");
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
          throw new RuntimeException("can not set property when set for "+ target +" and clazz "+clazz + " field "+ fieldName);
        }
      }else if (Number.class.isAssignableFrom(propertyDescriptor.getPropertyType()) && value == null) {
          try {
            BeanUtils.setProperty(target, fieldName, "0");
          } catch (Exception e) {
            throw new RuntimeException("can not set property when set for "+ target +" and clazz "+clazz + " field "+ fieldName);
          }
      }
    }
  }

  public static <T> void onUpdate(T target){
    try {
      PropertyUtils.setProperty(target, updateDatetimeKey, String.valueOf(System.currentTimeMillis() / 1000));
      PropertyUtils.setProperty(target, updateUserIdKey, 0);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
      return;
    }
  }

  public static <T> void onInsert(T target){
    long time = System.currentTimeMillis();
    try {
      PropertyUtils.setProperty(target, updateDatetimeKey, String.valueOf(System.currentTimeMillis() / 1000));
      PropertyUtils.setProperty(target, updateUserIdKey, 0);

      PropertyUtils.setProperty(target, createDatetimeKey, String.valueOf(System.currentTimeMillis() / 1000));
      PropertyUtils.setProperty(target, createUserIdKey, 0);

      PropertyUtils.setProperty(target, delFlgKey, 0);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {

    }
  }
}